package com.zhuangjie.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhaungjie.base.conduit.TypeR;
import com.zhaungjie.base.utils.PropertiesCopyUtils.PropertiesCopy;
import com.zhuangjie.order.entity.DeliveryInfo;
import com.zhuangjie.order.enums.OrderState;
import com.zhuangjie.order.feign.UserFeignService;
import com.zhuangjie.order.mapper.DeliveryInfoMapper;
import com.zhuangjie.order.pojo.DeliveryInfoForRider;
import com.zhuangjie.order.service.DeliveryInfoService;
import com.zhuangjie.shop.enums.BusinessTypeEnum;
import com.zhuangjie.shop.helper.ShopModuleTokenDataProvider;
import com.zhuangjie.user.entity.AddressBook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhuangjie
 * @since 2023-11-24
 */
@Service
public class DeliveryInfoServiceImpl extends ServiceImpl<DeliveryInfoMapper, DeliveryInfo> implements DeliveryInfoService {

    @Autowired
    private UserFeignService userFeignService;

    @Override
    public void saveDeliveryInfo(Long orderId, Long addressBookId) throws Exception {
        // 保存用户配送信息到单独的表-保留起来
        AddressBook addressBook = TypeR.extract(userFeignService.getAddressBookById(addressBookId));
        DeliveryInfo deliveryInfo = PropertiesCopy.type(AddressBook.class, DeliveryInfo.class)
                .config(c->c.ignoreProperties(DeliveryInfo::getId))
                .produce(addressBook);
        deliveryInfo.setOrderId(orderId);
        this.save(deliveryInfo);
    }

    @Override
    public DeliveryInfoForRider queryForCreateDeliveryOrder(Long orderId) {
        Long shopId = ShopModuleTokenDataProvider.getShopId();
        // orderId该订单必须是shopId店铺的，否则无法查到，否则返回空，就会报异常
        // 且要求订单的状态（<=接单中）与交付类型（配送）
        return this.baseMapper.selectDeliveryInfoForOrderWithShop(shopId, orderId, OrderState.ORDER_ACCEPTED, BusinessTypeEnum.DELIVERY.getValue());
    }
}
